package com.cloud.school.bus.teacherhelper.modules.home.recorder;

import java.io.File;

import com.android.support.jhf.debug.DebugLog;
import com.android.support.jhf.universalimageloader.core.DisplayImageOptions;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.entitys.Picture;
import com.cloud.school.bus.teacherhelper.modules.SlidingActivity;
import com.cloud.school.bus.teacherhelper.modules.home.UploadFileStuSelectedActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.SurfaceTexture;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Video.Thumbnails;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.RelativeLayout.LayoutParams;

@SuppressLint("NewApi")
public class FFmpegPreviewActivity extends BaseActivity implements
		TextureView.SurfaceTextureListener, OnClickListener,
		OnCompletionListener {

	private String path;
//	private String imagePath;
	private TextureView surfaceView;
	private Button cancelBtn;
	private Button mNextButton;
	private Button mSaveButton;
	private MediaPlayer mediaPlayer;
	private ImageView imagePlay;
	private ViewGroup previewImageParent;
	private ImageView previrePlayBg;

	public DisplayImageOptions mDisplayImageOptions;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ffmpeg_preview);

		cancelBtn = (Button) findViewById(R.id.play_cancel);
		cancelBtn.setOnClickListener(this);
		mNextButton = (Button)findViewById(R.id.play_next);
		mNextButton.setOnClickListener(this);
		mSaveButton = (Button)findViewById(R.id.saveButton);
		mSaveButton.setOnClickListener(this);

		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		surfaceView = (TextureView) findViewById(R.id.preview_video);

		RelativeLayout preview_video_parent = (RelativeLayout) findViewById(R.id.preview_video_parent);
		LayoutParams layoutParams = (LayoutParams) preview_video_parent
				.getLayoutParams();
		layoutParams.width = displaymetrics.widthPixels;
		layoutParams.height = displaymetrics.widthPixels;
		preview_video_parent.setLayoutParams(layoutParams);

		surfaceView.setSurfaceTextureListener(this);
		surfaceView.setOnClickListener(this);

		path = getIntent().getStringExtra("path");
//		imagePath = getIntent().getStringExtra("imagePath");
//		Toast.makeText(this, path, Toast.LENGTH_LONG).show();
		imagePlay = (ImageView) findViewById(R.id.previre_play);
		imagePlay.setOnClickListener(this);
		previewImageParent = (ViewGroup) findViewById(R.id.preview_image_parent);
		previewImageParent.setOnClickListener(this);
		previrePlayBg = (ImageView) findViewById(R.id.previre_play_bg);
		if (path.endsWith("MP4")
				|| path.endsWith("mp4")) {
			Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(
					path, Thumbnails.MINI_KIND);
			if (null != bitmap) {
				previrePlayBg.setImageBitmap(bitmap);
			}
		}

		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
	}

	@Override
	protected void onStop() {
		if (mediaPlayer.isPlaying()) {
			mediaPlayer.pause();
//			imagePlay.setVisibility(View.GONE);
//			previrePlayBg.setVisibility(View.GONE);
			previewImageParent.setVisibility(View.GONE);
		}
		super.onStop();
	}

	private void prepare(Surface surface) {
		try {
			mediaPlayer.reset();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			// 设置需要播放的视频
			mediaPlayer.setDataSource(path);
			// 把视频画面输出到Surface
			mediaPlayer.setSurface(surface);
			mediaPlayer.setLooping(false);
			mediaPlayer.prepare();
			mediaPlayer.seekTo(0);
		} catch (Exception e) {
		}
	}

	@Override
	public void onSurfaceTextureAvailable(SurfaceTexture arg0, int arg1,
			int arg2) {
		prepare(new Surface(arg0));
	}

	@Override
	public boolean onSurfaceTextureDestroyed(SurfaceTexture arg0) {
		return false;
	}

	@Override
	public void onSurfaceTextureSizeChanged(SurfaceTexture arg0, int arg1,
			int arg2) {

	}

	@Override
	public void onSurfaceTextureUpdated(SurfaceTexture arg0) {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.play_cancel:
//			stop();
			retakeVideo();
			break;
		case R.id.preview_image_parent:
		case R.id.previre_play:
			DebugLog.logI("preview_image_parent");
			if (!mediaPlayer.isPlaying()) {
				mediaPlayer.start();
			}
//			previrePlayBg.setVisibility(View.GONE);
//			imagePlay.setVisibility(View.GONE);
			previewImageParent.setVisibility(View.GONE);
			break;
		case R.id.preview_video:
			if (mediaPlayer.isPlaying()) {
				mediaPlayer.pause();
//				previrePlayBg.setVisibility(View.VISIBLE);
//				imagePlay.setVisibility(View.VISIBLE);
				previewImageParent.setVisibility(View.VISIBLE);
			}
			break;
		case R.id.play_next:{
			//下一步
			next();
			break;
		}
		case R.id.saveButton:{
			saveVideo();
			break;
		}
		default:
			break;
		}
	}

	private void stop() {
		mediaPlayer.stop();
	}
	
	/**
	 * 下一步,进行上传
	 */
	private void next() {
		stop();
		Picture picture = new Picture();
		picture.setPicturePath(path);
		Intent intent = new Intent(mContext,
				UploadFileStuSelectedActivity.class);
		intent.putExtra("title", getString(R.string.upload_video));
		intent.putExtra("index", -1);
		intent.putExtra("picture", picture);
		startActivityForResult(intent, 0);
	}
	
	/**
	 * 重拍视频
	 */
	private void retakeVideo() {
		//暂停播放
		stop();
		//重拍删除视频和图片
		File videoFile = new File(path);
//		File imageFile = new File(imagePath);
		videoFile.delete();
//		imageFile.delete();
		//销毁自己跳转到视频拍摄界面
		Intent intent = new Intent(this, FFmpegRecorderActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		finish();
	}
	
	/**
	 * 保存视频
	 */
	private void saveVideo(){
		showSaveVideoDialog();
	}
	
	private void showSaveVideoDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext, R.style.CustomAlertDialog);
		customAlertDialog.setTitleMessage("提示", Color.BLACK);
		customAlertDialog.setMessage("是否要保存到视频草稿箱");
		customAlertDialog.setLeftButton("保存", new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				stop();
				Intent intent = new Intent(mContext, SlidingActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
				finish();
			}
		});
		customAlertDialog.setRightButton("取消", new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				
			}
		});
		customAlertDialog.show();
	}

//	@Override
//	public void onBackPressed() {
//		retakeVideo();
//	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(keyCode == KeyEvent.KEYCODE_BACK){
			retakeVideo();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
//		imagePlay.setVisibility(View.VISIBLE);
//		previrePlayBg.setVisibility(View.VISIBLE);
		previewImageParent.setVisibility(View.VISIBLE);
		stop();
	}
}
